<template>
  <div class="app-container">
    <avue-crud
      ref="crud"
      v-model="form"
      :data="data"
      :option="option"
      :page.sync="page"
      :search.sync="search"
      :upload-before="uploadBefore"
      :upload-after="uploadAfter"
      :upload-error="uploadError"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
      @size-change="sizeChange"
      @current-change="currentChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @search-reset="searchChange"
      @search-change="searchChange"
    >
      <template slot="status" slot-scope="scope">
        <avue-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" :dic="scope.dic" @click="switchChange($event, scope)" />
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { getList, del, update, add, start, stop } from '@/api/operation/banner';
import CONFIG from '@/config/index';
import DIC from '@/config/dicData';

export default {
  data() {
    return {
      imgURL: '',
      fullURL: '',
      page: {
        currentPage: 1,
        pageSize: 10
      },
      search: {},
      form: {},
      data: [],
      loading: false,
      option: {
        title: '轮播图',
        align: 'center',
        menuAlign: 'center',
        viewBtn: true,
        columnBtn: false,
        index: true,
        column: [
          {
            label: '标题',
            prop: 'title',
            rules: [{
              required: true,
              message: '请输入标题',
              trigger: 'blur'
            }]
          },
          {
            label: '图片',
            prop: 'imgURL',
            type: 'upload',
            span: 24,
            limit: 1,
            accept: ['image/jpeg', 'image/png'],
            listType: 'picture-img',
            dataType: 'string',
            action: '/api/qiniu/fileUpload',
            propsHttp: {
              home: CONFIG.uploadUrl,
              url: 'fileName',
              fileName: 'imgFile'
            },
            tip: `只能上传jpg/png图片，且不超过${CONFIG.bannerLimitSize}M`,
            rules: [{
              required: true,
              message: '请上传图片',
              trigger: 'change'
            }]
          },
          {
            label: '跳转链接',
            prop: 'path'
          },
          {
            label: '上传日期',
            prop: 'createTime',
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            readonly: true
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            value: '0',
            dataType: 'number',
            slot: true,
            dicData: DIC.banner_status
          },
          {
            label: '排序',
            prop: 'sort',
            value: 1,
            type: 'number'
          }
        ]
      }
    };
  },
  methods: {
    onLoad(page) {
      this.loading = true;
      const pageNum = this.page.currentPage;
      const pageSize = this.page.pageSize;
      getList(pageNum, pageSize)
        .then(res => {
          const data = res.data;
          this.loading = false;
          this.page.total = data.total;
          const result = data.rows;
          this.data = result;
        });
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.onLoad();
    },
    currentChange(val) {
      this.page.currentPage = val;
      this.onLoad();
    },
    refreshChange() {
      this.onLoad();
      this.$message.success('刷新成功');
    },
    rowSave(row, done, loading) {
      const payload = {
        imgURL: this.form.imgURL,
        fullURL: this.form.fullURL,
        status: this.form.status,
        sort: this.form.sort,
        title: this.form.title
      }
      add(payload).then(() => {
        this.$message.success('新增成功')
        done();
        this.onLoad();
      }).catch(() => {
        loading()
      })
    },
    rowUpdate(row, index, done, loading) {
      update(row).then((res) => {
        this.$message.success('修改成功')
        done()
        this.onLoad();
      }).catch((err) => {
        this.$message.error('修改失败' + err);
      });
    },
    rowDel(row, index) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return del(row.id)
      }).then(() => {
        this.$message.success('删除成功')
        this.onLoad();
      })
    },
    switchChange(value, scope) {
      if (value === '0') {
        stop(scope.row.id).then((res) => {
          this.$message.success('操作成功')
        })
      } else {
        start(scope.row.id).then((res) => {
          this.$message.success('操作成功')
        })
      }
    },
    searchChange(params, done) {
      if (done) done();
      this.params = params;
      this.page.currentPage = 1;
      this.onLoad();
      this.$message.success('搜索成功')
    },
    uploadBefore(file, done, loading) {
      console.log('uploadBefore', file);
      const limitSize = file.size / 1024 / 1024 < CONFIG.bannerLimitSize;
      if (!limitSize) {
        this.$message.error('图片大小超过限制');
        this.form.imgURL = '';
        loading();
        return
      }
      done();
    },
    uploadAfter(res, done) {
      this.form.fullURL = CONFIG.uploadUrl + res.fileName;
      done();
    },
    uploadError(error, column) {
      console.log('uploadError', error, column);
      this.$message.error('上传图片失败，请重试');
    }
  }
};
</script>

<style lang="scss" scoped>
  .avue-upload__icon {
    line-height: 178px !important;
  }
</style>
